package com.nbjtjc.safe.api.know;

import cn.hutool.core.util.ObjectUtil;
import com.nbjtjc.safe.annotation.SysLog;
import com.nbjtjc.safe.bean.Page;
import com.nbjtjc.safe.bean.Result;
import com.nbjtjc.safe.model.know.SafeKnowLabel;
import com.nbjtjc.safe.model.know.SafeKnowledge;
import com.nbjtjc.safe.model.sys.SysFile;
import com.nbjtjc.safe.service.know.SafeKnowledgeService;
import com.nbjtjc.safe.util.FileUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * 知识点的接口
 */
@RestController
@RequestMapping("/knowledge")
@CrossOrigin("*")
public class KnowController {

    @Autowired
    private SafeKnowledgeService safeKnowledgeService;
    @Autowired
    private FileUtil fileUtil;
    /**
     * 添加知识库里面的知识点
     * @param safeKnowledge
     * @return
     */
    @SysLog("添加知识库中的知识点")
    @RequestMapping(value = "/add",method = {RequestMethod.POST})
    public Result add(SafeKnowledge safeKnowledge) {
        Result result=new Result();
        try {
            result=safeKnowledgeService.add(safeKnowledge);
        } catch (Exception e) {
            e.printStackTrace();
            result.setFalse(e.getMessage());
        }
        return result;
    }

    @SysLog("批量添加知识库中的知识点")
    @RequestMapping(value = "/addBatch",method = {RequestMethod.POST})
    public Result addBatch(){
        Result result=new Result();

        return result;
    }
    /**
     * 更新知识库里面的知识点
     * @param safeKnowledge
     * @return
     */
    @SysLog("更新知识点")
    @RequestMapping(value = "/update",method = {RequestMethod.POST})
    public Result update(SafeKnowledge safeKnowledge) {
        Result result=new Result();
        try {
            result=safeKnowledgeService.update(safeKnowledge);
        } catch (Exception e) {
            e.printStackTrace();
            result.setFalse(e.getMessage());
        }
        return result;
    }

    /**
     * 删除知识点
     * @param safeKnowId
     * @return
     */
    @SysLog("更新知识点")
    @RequestMapping(value = "/delete",method = {RequestMethod.POST})
    public Result delete(int safeKnowId) {
        Result result=new Result();
        try {
            result=safeKnowledgeService.delete(safeKnowId);
        } catch (Exception e) {
            e.printStackTrace();
            result.setFalse(e.getMessage());
        }
        return result;
    }

    @RequestMapping(value = "/find",method = {RequestMethod.POST})
    public Result find(SafeKnowLabel safeKnowLabel) {
        Result result=new Result();
        try {
            result=safeKnowledgeService.find(safeKnowLabel);
        } catch (Exception e) {
            e.printStackTrace();
            result.setFalse(e.getMessage());
        }
        return result;
    }
    @RequestMapping(value = "/findJson",method = {RequestMethod.POST})
    public Result findJson(@RequestBody SafeKnowLabel safeKnowLabel) {
        Result result=new Result();
        try {
            result=safeKnowledgeService.find(safeKnowLabel);
        } catch (Exception e) {
            e.printStackTrace();
            result.setFalse(e.getMessage());
        }
        return result;
    }

    /**
     * 知识点和标签进行绑定，俗称打标签
     * @return
     */
    @SysLog("批量打标签")
    @RequestMapping(value = "/bindLabelBatch",method = {RequestMethod.POST})
    public Result bindLabelBatch(@RequestParam("knowIds") List<Integer> knowIds
            ,@RequestParam("labels")List<String> labels) {
        Result result=new Result();
        try {
            result=safeKnowledgeService.bindLabelBatch(knowIds,labels);
        } catch (Exception e) {
            e.printStackTrace();
            result.setFalse(e.getMessage());
        }
        return result;
    }

    /**
     * 批量删除标签
     * @return
     */
    @SysLog("批量删除标签")
    @RequestMapping(value = "/deleteLabelBatch",method = {RequestMethod.POST})
    public Result deleteLabelBatch(@RequestParam("knowIds") List<Integer> knowIds
            ,@RequestParam("labels")List<String> labels) {
        Result result=new Result();
        try {
            result=safeKnowledgeService.deleteLabelBatch(knowIds,labels);
        } catch (Exception e) {
            e.printStackTrace();
            result.setFalse(e.getMessage());
        }
        return result;
    }

    /**
     * 复制知识点和知识点对应的标签
     * @param fromCompanyId
     * @param toCompanyId
     * @return
     */
    @GetMapping("/copyKnowledge/{fromCompanyId}/{toCompanyId}")
    public Result copyKnowledge(@PathVariable("fromCompanyId") int fromCompanyId,@PathVariable("toCompanyId") int toCompanyId){
         return Result.success(safeKnowledgeService.copyKnowledge(fromCompanyId,toCompanyId));
    }

    @PostMapping("/importKnowledge")
    public Result importKnowledge(HttpServletRequest request,int companyId){
        Result result = new Result<>();
        try {
            // 解析器解析request的上下文未登录或者过期
            CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
            // 先判断request中是否包含mutipart类型的数据
            if (multipartResolver.isMultipart(request)) {
                // 再将request中得数据转化成multipart类型的数据f
                MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
                List<MultipartFile> multipartFiles = multiRequest.getFiles("file");
                Iterator iterator = multiRequest.getFileNames();
                while (iterator.hasNext()) {
                    MultipartFile file = multiRequest.getFile((String) iterator.next());
                    safeKnowledgeService.addBatch(file,companyId);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.setFalse("上传失败" + e.getMessage());
        }
        return result;
    }

    @GetMapping("/downloadKnowTemplate")
    public void downloadKnowTemplate(HttpServletResponse response) throws FileNotFoundException {
        File file= ResourceUtils
                .getFile("classpath:inoutPutTemplates/knowledgeTemplate.xlsx");
        if (ObjectUtil.isNotNull(file)&&file.exists()) {
            BufferedInputStream bis = null;
            byte[] buff = new byte[1024];
            response.setDateHeader("Expires", 0);
            response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
            response.addHeader("Cache-Control", "post-check=0, pre-check=0");
            response.setHeader("Pragma", "no-cache");
            response.setContentType("image/jpeg");
            response.setHeader("Content-Disposition", "attachment;filename=" + file.getName());
            try (ServletOutputStream outputStream = response.getOutputStream()) {
                bis = new BufferedInputStream(new FileInputStream(file));
                int i = bis.read(buff);
                while (i != -1) {
                    outputStream.write(buff, 0, i);
                    outputStream.flush();
                    i = bis.read(buff);
                }
            } catch (IOException e) {
                throw new FileNotFoundException("输出文件时报错：" + e.getMessage());
            } finally {
                if (bis != null) {
                    try {
                        bis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        } else {
            throw new FileNotFoundException("文件没有找到");
        }
    }
}
